<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" class="el-breadcrumb">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <!-- 添加角色按钮区 -->
          <el-button type="primary" @click="addRolesDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['dbBottom', 'vcenter', i1 === 0 ? 'dbTop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRigthByID(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'dbTop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRigthByID(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRigthByID(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre> {{scope.row.children}}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="角色操作" width="350px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRolse(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delRole(scope.row)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-share"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRigthDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        show-checkbox
        node-key="id"
        :data="rightsList"
        :props="treeProps"
        :default-expand-all="true"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRigthDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <el-dialog title="提示" :visible.sync="addRolesDialogVisible" width="30%">
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="100px"
        :rules="addFromRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRolesDialogVisible"
      width="30%"
    >
      <el-form
        ref="editFormRef"
        :model="editInfo"
        label-width="80px"
        :rules="editFromRules"
      >
        <el-form-item label="角色名称">
          <el-input v-model="editInfo.roleName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 控制分配权限对话框的显示隐藏
      setRigthDialogVisible: false,
      // 所有权限数据
      rightsList: [],
      // 树形控件的属性绑定控件
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的数组
      defKeys: [105, 116],
      // 当前分配权限的id
      roleId: '',
      // 控制添加角色对话框的显示与隐藏
      addRolesDialogVisible: false,
      // 控制编辑角色对话框的显示隐藏
      editRolesDialogVisible: false,
      // 添加角色对象
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色信息
      editInfo: {},
      // 添加表单的验证规则对象
      addFromRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '用户名的长度在1~10字符之间',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '用户名的长度在3~10字符之间',
            trigger: 'blur'
          }
        ]
      },
      editFromRules: {
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '用户名的长度在3~10字符之间',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status === 200) {
        this.rolesList = res.data
      } else {
        this.$message.error('获取权限列表失败')
      }
    },
    // 根据id删除对应的权限
    async removeRigthByID(role, rightId) {
      const confirmResult = await this.$confirm(
        '确定删除该角色下的该权限?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      console.log(res)
      if (res.meta.status === 200) {
        this.$message.success('删除权限成功')
        // this.getRolesList()
        role.children = res.data
      } else {
        this.$message.error('删除失败！')
      }
    },
    // 展示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      this.setRigthDialogVisible = true
      console.log(res)
      if (res.meta.status === 200) {
        this.rightsList = res.data

        this.getLeafKeys(role, this.defKeys)
      } else {
        this.$message.error('获取权限失败')
      }
    },
    // 通过递归的形式，获取角色下所有三级权限的id,并保存到defKys数组中
    getLeafKeys(node, arr) {
      // 如果当前node节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听关闭分配权限对话框的方法
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 点击确定分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status === 200) {
        this.$message.success('分配权限成功')
        this.getRolesList()
        this.setRigthDialogVisible = false
      } else {
        this.$message.error('分配权限失败')
      }
    },
    // 点击添加角色
    addRoles() {
      console.log(this.addForm)
      this.$refs.addFormRef.validate(async (valid, obj) => {
        if (valid) {
          const { data: res } = await this.$http.post('roles', this.addForm)
          console.log(res)
          if (res.meta.status === 201) {
            this.$message.success('添加角色成功')
            this.getRolesList()
            this.addRolesDialogVisible = false
          }
        } else {
          console.log(obj)
        }
      })
    },
    // 删除角色
    async delRole(roleInfo) {
      console.log(roleInfo)
      const res = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => {
        return err
      })
      // 如果用户确认删除，则返回值为字符串confirm
      // 如果用户取消删除，则返回值为cancel
      if (res === 'confirm') {
        const { data: res } = await this.$http.delete(`roles/${roleInfo.id}`)
        console.log(res)
        if (res.meta.status === 200) {
          this.$message.success('删除成功')
          this.getRolesList()
        } else {
          this.$message.error('删除失败')
        }
      } else if (res === 'cancel') {
        this.$message.info('取消删除')
      } else {
        this.$message.error('删除错误')
      }
    },
    // 点击显示修改角色对话框
    async editRolse(rolesInfo) {
      this.editRolesDialogVisible = true
      console.log(rolesInfo)
      const { data: res } = await this.$http.get(`roles/${rolesInfo.id}`)
      if (res.meta.status === 200) {
        this.editInfo = res.data
      }
    },
    // 点击确定按钮提交编辑信息
    editSubmit() {
      console.log(this.editInfo)
      this.$refs.editFormRef.validate(async valid => {
        console.log(valid)
        if (valid) {
          const { data: res } = await this.$http.put(
            `roles/${this.editInfo.roleId}`,
            {
              roleName: this.editInfo.roleName,
              roleDesc: this.editInfo.roleDesc
            }
          )
          console.log(res)
          if (res.meta.status === 200) {
            this.editRolesDialogVisible = false
            this.getRolesList()
            this.$message.success('修改角色信息成功')
          } else {
            this.$message.error('修改角色信息失败')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.dbTop {
  border-top: 1px solid #eee;
}
.dbBottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
.el-tree {
  height: 500px;
  overflow: scroll;
  /* position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%); */
}
</style>
